import { notification } from 'antd';
import { history, getDvaApp } from 'umi';
import {
  MessageOutlined,
  SafetyOutlined,
  FileProtectOutlined,
  ControlOutlined,
  NotificationOutlined,
  IssuesCloseOutlined,
  AuditOutlined,
  AlertOutlined,
} from '@ant-design/icons';
import API from './api';
const transformMenu = (menu) => {
  const iconList = {
    系统管理: <ControlOutlined />,
    通知中心: <NotificationOutlined />,
    网络安全防护: <SafetyOutlined />,
    网络安全信息共享和通报: <MessageOutlined />,
    网络安全事件应急处置: <FileProtectOutlined />,
    必选功能管理: <IssuesCloseOutlined />,
    考核管理: <AuditOutlined />,
    安全态势感知预警: <AlertOutlined />,
  };
  menu.forEach((item) => {
    const icon = iconList[item.name];
    if (icon) {
      item.icon = icon;
    }
  });
  return menu;
};
const errorHandler = (error) => {
  getDvaApp()?._store.dispatch({
    type: 'load/setLoading',
    payload: false,
  });
  const status = error.response?.status;
  const codeMessage = {
    401: '用户没有权限',
    403: '禁止访问',
    404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
    500: '服务器发生错误，请检查服务器。',
    502: '网关错误。',
    503: '服务不可用，服务器暂时过载或维护。',
    504: '网关超时。',
  };
  if (history.location.pathname === '/login') {
    let msg = error.data?.t;
    if (msg === 'Bad credentials') {
      msg = '用户名或密码错误';
    }
    notification.destroy();
    notification.error({
      message: error.data.desc || '请求错误',
      description: msg,
    });
    return null;
  }
  if (status === 401) {
    notification.destroy();
    notification.error({
      message: error.data.desc || '登录已过期，请重新登录',
      description: error.data?.t,
      duration: 2,
    });
    window.localStorage.clear();
    // history.push('/login');
    return null;
  }
  notification.destroy();
  notification.error({
    message: codeMessage[status] || '请求错误',
    description: error.data?.desc,
  });
  return null;
};

export const request = {
  errorConfig: {
    adaptor: (resData) => {
      return {
        ...resData,
        success: resData.code == '0001',
      };
    },
  },
  errorHandler,
  middlewares: [],
  requestInterceptors: [
    async (url, options) => {
      getDvaApp()?._store.dispatch({
        type: 'load/setLoading',
        payload: true,
      });
      const jwt = localStorage.getItem('jwt');
      if (jwt) {
        const headers = {
          jwt,
        };
        return {
          url: url,
          options: { ...options, headers: headers },
        };
      }
    },
  ],
  responseInterceptors: [
    (response) => {
      const jwt = response.headers.get('jwt');
      if (jwt) {
        localStorage.setItem('jwt', jwt);
      }
      getDvaApp()?._store.dispatch({
        type: 'load/setLoading',
        payload: false,
      });
      return response;
    },
  ],
  prefix: '/jiaotong',
};

export const getInitialState = async () => {
  const fetchUserInfo = async () => {
    const res = await API.getCurrentUser();
    if (res?.t) {
      const data = res.t;
      const username = data.name;
      const userId = data.id;
      const orgId = data.currentOrg.id;
      const orgName = data.currentOrg.name || '无';
      const menuList = data.currentMenuList;
      const loginName = data.username;
      const userRoleId = data.orgIdMapRoleList[orgId]
        .map((el) => {
          return el.id;
        })
        .join(',');
      const orgList = data.orgList;
      return {
        orgName,
        username,
        userId,
        orgId,
        orgName,
        userRoleId,
        orgList,
        loginName,
        menuList: transformMenu(menuList),
      };
    } else {
      return {};
    }
  };
  if (history.location.pathname !== '/login') {
    const token = encodeURIComponent(history.location.query.token || '');
    const jwt = localStorage.getItem('jwt');
    if (token) {
      // const res = await API.getJwt({ token });
      try {
        const res = await API.forwardLogin({ token });
        await API.login_processOther(res.t);
        const info = await fetchUserInfo();
        return {
          fetchUserInfo,
          info,
        };
      } catch (error) {
        notification.error({
          message: '登录已过期，请重新登录',
          duration: 2,
        });
        window.location.href =
          'http://223.68.143.71:9091/uipmp/web/jiangsu_traffic/doWork';
      }
    } else if (jwt) {
      try {
        const info = await fetchUserInfo();
        return {
          fetchUserInfo,
          info,
        };
      } catch (error) {
        notification.error({
          message: '登录已过期，请重新登录',
          duration: 2,
        });
        window.location.href =
          'http://223.68.143.71:9091/uipmp/web/jiangsu_traffic/doWork';
      }
    } else {
      notification.error({
        message: '登录已过期，请重新登录',
        duration: 2,
      });
      window.location.href =
        'http://223.68.143.71:9091/uipmp/web/jiangsu_traffic/doWork';
    }
  }
  return { fetchUserInfo, info: {} };
};
